import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-05-21
 * Time: 17:12
 */
public class test4 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if(matrix==null || matrix.length==0 || matrix[0].length==0){
            return null;
        }
        // 定义行和列
        int row = 0;
        int col = 0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        // 是否访问过
        boolean[][] visited = new boolean[rows][cols];
        // 总数
        int total = rows*cols;
        int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}};
        int directionIndex = 0;
        for(int i=0;i<total;i++){
            order.add(matrix[row][col]);
            visited[row][col] = true;
            // 进行移动
            int nextRow = row + directions[directionIndex][0];
            int nextCol = col + directions[directionIndex][1];
            // 进行转换
            if(nextRow<0 || nextRow>=rows || nextCol<0 || nextCol>=cols || visited[nextRow][nextCol]==true){
                directionIndex = (directionIndex+1)%4;
            }
            row += directions[directionIndex][0];
            col += directions[directionIndex][1];
        }
        return order;
    }
}
